﻿using System;
using System.Runtime.InteropServices;
using System.Text;

namespace CubeStone.Wang.Utilities.Config
{
    /// <summary>
    /// Ini文件读写类。
    /// </summary>
    public class IniFile
    {
        [DllImport("kernel32")]
        private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);

        [DllImport("kernel32")]
        private static extern int GetPrivateProfileString(string section, string key, string defVal, StringBuilder retVal, int size, string filePath);

        [DllImport("kernel32")]
        private static extern int GetPrivateProfileString(string section, string key, string defVal, Byte[] retVal, int size, string filePath);

        public IniFile(string iniPath)
        {
            Path = iniPath;
        }

        public string Path { set; get; }

        /// <summary>
        /// 写Ini文件
        /// </summary>
        /// <param name="Section">节</param>
        /// <param name="Key">键</param>
        /// <param name="Value">值</param>
        public void IniWriteValue(string section, string key, string value)
        {
            WritePrivateProfileString(section, key, value, this.Path);
        }

        /// <summary>
        /// 读取Ini文件(最大255个字节)
        /// </summary>
        /// <param name="Section">节</param>
        /// <param name="Key">键</param>
        /// <returns>string</returns>
        public string IniReadValue(string section, string key)
        {
            StringBuilder temp = new StringBuilder(255);
            int i = GetPrivateProfileString(section, key, string.Empty, temp, 255, this.Path);
            return temp.ToString();
        }

        /// <summary>
        /// 读取Ini文件(最大255个字节)
        /// </summary>
        /// <param name="Section">节</param>
        /// <param name="Key">键</param>
        /// <returns>byte[]</returns>
        public byte[] IniReadValues(string section, string key)
        {
            byte[] temp = new byte[255];
            int i = GetPrivateProfileString(section, key, string.Empty, temp, 255, this.Path);
            return temp;
        }


        /// <summary>
        /// 删除Ini文件下所有段落
        /// </summary>
        public void ClearAllSection()
        {
            IniWriteValue(null, null, null);
        }

        /// <summary>
        /// 删除Ini文件中指定节下的所有键
        /// </summary>
        /// <param name="Section"></param>
        public void ClearSection(string section)
        {
            IniWriteValue(section, null, null);
        }
    }
}